package com.party.admin.web.controller.crowdfund;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.party.admin.biz.activity.ActivityBizService;
import com.party.admin.biz.crowdfund.ProjectBizService;
import com.party.admin.biz.crowdfund.ProjectTransferBizService;
import com.party.admin.biz.crowdfund.RepresentBizService;
import com.party.admin.biz.distribution.DistributionBizService;
import com.party.admin.biz.file.ExcelExportService;
import com.party.admin.biz.file.FileBizService;
import com.party.admin.biz.order.OrderBizService;
import com.party.admin.biz.workflow.BusinessInstanceBizService;
import com.party.admin.utils.RealmUtils;
import com.party.admin.utils.excel.ExportExcel;
import com.party.admin.web.annotation.UserOperate;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.output.crowdfund.ListForTargetOutput;
import com.party.admin.web.dto.output.crowdfund.ProjectForActivityOutput;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.redis.StringJedis;
import com.party.common.utils.BigDecimalUtils;
import com.party.common.utils.DateUtils;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.copartner.TargetCopartner;
import com.party.core.model.counterfoil.Counterfoil;
import com.party.core.model.counterfoil.CounterfoilBusiness;
import com.party.core.model.crowdfund.*;
import com.party.core.model.distributor.DistributorRelation;
import com.party.core.model.log.BehaviorType;
import com.party.core.model.member.Member;
import com.party.core.model.member.MemberGroup;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.copartner.ITargetCopartnerService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.counterfoil.ICounterfoilBusinessService;
import com.party.core.service.counterfoil.ICounterfoilService;
import com.party.core.service.crowdfund.*;
import com.party.core.service.distributor.IDistributorCountService;
import com.party.core.service.distributor.IDistributorDetailService;
import com.party.core.service.distributor.IDistributorRelationService;
import com.party.core.service.member.IMemberAdministratorService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.order.IOrderFormService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 众筹控制器 Created by wei.li
 *
 * @date 2017/2/17 0017
 * @time 15:37
 */
@SuppressWarnings("all")
@Controller
@RequestMapping(value = "/crowdfund/project")
public class ProjectController {

    @Autowired
    private ProjectBizService projectBizService;

    @Autowired
    private RepresentBizService representBizService;

    @Autowired
    private IActivityService activityService;

    @Autowired
    private IOrderFormService orderFormService;

    @Autowired
    private ActivityBizService activityBizService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private IDistributorRelationService distributorRelationService;

    @Autowired
    private ICrowdfundEventService crowdfundEventService;

    @Autowired
    private IMemberService memberService;

    @Autowired
    private IProjectReviseService projectReviseService;

    @Autowired
    private ExcelExportService excelExportService;

    @Autowired
    private BusinessInstanceBizService businessInstanceBizService;

    @Autowired
    private ITargetCopartnerService targetCopartnerService;

    @Autowired
    private FileBizService fileBizService;

    @Autowired
    private ITargetProjectService targetProjectService;

    @Autowired
    private ProjectTransferBizService projectTransferBizService;

    @Autowired
    private ISupportTransferService supportTransferService;

    @Autowired
    private OrderBizService orderBizService;

    @Autowired
    private CosBizService cosBizService;

    @Autowired
    private ISupportService supportService;
    @Autowired
    private IProjectTransferService projectTransferService;
    @Autowired
    private StringJedis stringJedis;
    @Autowired
    private DistributionBizService distributionBizService;
    @Autowired
    private IDistributorDetailService distributorDetailService;
    @Autowired
    private IDistributorCountService distributorCountService;
    @Autowired
    private IMemberAdministratorService memberAdministratorService;
    @Autowired
    private ICounterfoilService counterfoilService;
    @Autowired
    private ICounterfoilBusinessService counterfoilBusinessService;

    @Autowired
    private IMemberGroupService memberGroupService;

    //众筹转移已授权
    private static final int YET_AUTHORIZED = 1;
    //众筹转移成功
    private static final int YET_SUCCESS = 2;


    protected static Logger logger = LoggerFactory.getLogger(ProjectController.class);


    /**
     * 项目下联合发起
     *
     * @param id   项目编号
     * @param page 分页参数
     * @return 联合发起列表
     */
    @ResponseBody
    @RequestMapping(value = "listForTarget")
    public AjaxResult listForTarget(String id, Page page) {
        AjaxResult ajaxResult = new AjaxResult();

        List<ListForTargetOutput> listForTargetOutputList;
        try {
            listForTargetOutputList = representBizService.listForTarget(page, null, id);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.setDescription("系统异常");
            return ajaxResult;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("datas", listForTargetOutputList);
        map.put("page", page);
        ajaxResult.setSuccess(true);
        ajaxResult.setData(map);
        return ajaxResult;
    }

    /**
     * 众筹中的众筹
     *
     * @param id   项目编号
     * @param page 分页参数
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "crowdfunding")
    public AjaxResult crowdfunding(String id, Page page) {
        AjaxResult ajaxResult = new AjaxResult();
        if (Strings.isNullOrEmpty(id)) {
            ajaxResult.setDescription("众筹项目编号不能为空");
            return ajaxResult;
        }
        List<ProjectForActivityOutput> projectForActivityOutputList = projectBizService.projectForActivityList(false, id, page);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("datas", projectForActivityOutputList);
        map.put("page", page);
        ajaxResult.setSuccess(true);
        ajaxResult.setData(map);
        return ajaxResult;
    }

    /**
     * 众筹成功的众筹
     *
     * @param id   项目编号
     * @param page 分页参数
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "crowdfunded")
    public AjaxResult crowdfunded(String id, Page page) {
        AjaxResult ajaxResult = new AjaxResult();
        if (Strings.isNullOrEmpty(id)) {
            ajaxResult.setDescription("众筹项目编号不能为空");
            return ajaxResult;
        }
        List<ProjectForActivityOutput> projectForActivityOutputList = projectBizService.projectForActivityList(true, id, page);
        ajaxResult.setSuccess(true);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("datas", projectForActivityOutputList);
        map.put("page", page);
        ajaxResult.setData(map);
        return ajaxResult;
    }

    /**
     * 根据分销关系查询众筹列表
     *
     * @param relationId 分销关系
     * @param page       分页参数
     * @return 众筹列表
     */
    @RequestMapping(value = "listForDistributorId")
    public ModelAndView listForDistributorId(String id, String relationId, Page page) {
        ModelAndView modelAndView = new ModelAndView("activity/crowdfundList");
        modelAndView.addObject("isMultiple", false);
        modelAndView.addAllObjects(projectBizService.listForDistributorCommonActivity(id, relationId, page));
        return modelAndView;
    }

    /**
     * 众筹列表
     *
     * @param id                活动编号
     * @param page              分页参数
     * @param projectWithAuthor 众筹状态
     * @return 输出视图
     */
    @RequestMapping(value = "copartnerCrowList")
    public ModelAndView copartnerCrowList(ProjectWithAuthor projectWithAuthor, Page page) {
        page.setLimit(20);
        ModelAndView modelAndView = new ModelAndView("activity/copartnerCrowList");
        Integer isSuccess = projectWithAuthor.getIsSuccess();//先保存查询类型
        if (null != projectWithAuthor.getIsSuccess() && 0 == projectWithAuthor.getIsSuccess()) { // 众筹中
            projectWithAuthor.setIsSuccess(10);
        }
        List<ProjectForActivityOutput> projectForActivityOutputList = projectBizService.copartnerCrowList(projectWithAuthor, page);
        projectWithAuthor.setIsSuccess(isSuccess);
        modelAndView.addObject("list", projectForActivityOutputList);
        modelAndView.addAllObjects(distributionBizService.getDisData(projectWithAuthor.getRelationId()));
        modelAndView.addObject("page", page);
        modelAndView.addObject("projectWithAuthor", projectWithAuthor);//回传查询参数
        return modelAndView;
    }

    /**
     * 导出联合发起的众筹
     *
     * @param relationId 分销关系
     * @param name       名称
     * @param response   响应参数
     * @return
     */
    @ResponseBody
    @UserOperate(moduleName = "众筹项目-数据查看-联合发起的众筹列表", behaviorType = BehaviorType.EXPORT)
    @RequestMapping(value = "listForDistributorIdExport")
    public AjaxResult listForDistributorIdExport(String relationId, String name, HttpServletResponse response) {
        String fileName = name + "联合发起的众筹.xlsx";
        List<ProjectForActivityOutput> projectForActivityOutputList = projectBizService.listForDistributorId(relationId, null);
        try {
            ExportExcel exportExcel = new ExportExcel(fileName, ProjectForActivityOutput.class).setDataList(projectForActivityOutputList);
            String allPath = excelExportService.getExcelPath(fileName, "project", exportExcel);
            return AjaxResult.success((Object) allPath);
        } catch (IOException e) {
            logger.error("导出联合发起的众筹异常", e);
        }
        return AjaxResult.error("导出异常");
    }


    /**
     * 根据事件查询众筹列表
     *
     * @param projectWithAuthor 查询数据
     * @param page              分页参数
     * @return 交互数据
     */
    @RequestMapping(value = "listForEvent")
    public ModelAndView listForEvent(ProjectWithAuthor projectWithAuthor, Page page) {
        ModelAndView modelAndView = new ModelAndView("crowdfund/zcCrowdfund");
        if (Strings.isNullOrEmpty(projectWithAuthor.getEventId())) {
            return modelAndView;
        }
        //管理员数据权限控制
        Map<String, Object> params = RealmUtils.getMemberAdministrator(new HashMap<>(), memberAdministratorService);
        if (params.containsKey("memberId")) {
            projectWithAuthor.setMemberId(params.get("memberId").toString());
        }
        page.setLimit(20);
        projectWithAuthor.setDistribution(true);

        Integer isSuccess = projectWithAuthor.getIsSuccess();

        if (null != projectWithAuthor.getIsSuccess() && 0 == projectWithAuthor.getIsSuccess()) { // 众筹中
            projectWithAuthor.setIsSuccess(10);
        }
        projectWithAuthor.setPayType(0);//查询普通众筹
        List<ProjectForActivityOutput> projectForActivityOutputList = projectBizService.projectForActivityList(projectWithAuthor, page);
        Integer representNum = distributorRelationService.countForEvent(projectWithAuthor.getEventId());
        projectWithAuthor.setIsSuccess(isSuccess);


        //众筹成功
        if (null != projectWithAuthor.getIsSuccess() && 1 == projectWithAuthor.getIsSuccess()) {
            //成功金额
            ProjectAnalyze projectAnalyze = new ProjectAnalyze();
            projectAnalyze.setEventId(projectWithAuthor.getEventId());
            projectAnalyze.setIsSuccess(Constant.IS_CROWFUND_SUCCESS);
            projectAnalyze.setPayType(0);
            Double successfulAmount = projectService.sumProjectOREventAmount(projectAnalyze, 1);
            modelAndView.addObject("successfulAmount", successfulAmount);
        }

        //直接付款人数
        Integer directNum = projectService.dpCountForEvent(projectWithAuthor.getEventId(), null);

        // 众筹金额

        modelAndView.addObject("representNum", representNum);
        modelAndView.addObject("projectNum", page.getTotalCount());
        modelAndView.addObject("directNum", directNum);
        modelAndView.addObject("projectWithAuthor", projectWithAuthor);//回传查询参数
        modelAndView.addObject("list", projectForActivityOutputList);
        modelAndView.addObject("page", page);
        CrowdfundEvent crowdfundEvent = crowdfundEventService.get(projectWithAuthor.getEventId());
        modelAndView.addObject("crowdfundEvent", crowdfundEvent);
        modelAndView.addAllObjects(orderBizService.getOrderData(projectWithAuthor.getEventId(), 0));
        modelAndView.addAllObjects(activityBizService.putZipInfo(Constant.PRE_ZIP_URL + "event_success_" + projectWithAuthor.getEventId()));
        return modelAndView;
    }


    /**
     * 直接付款众筹
     *
     * @param projectWithAuthor
     * @param page
     * @return
     */
    @RequestMapping(value = "dpListForEvent")
    public ModelAndView dpListForEvent(ProjectWithAuthor projectWithAuthor, Page page) {
        ModelAndView modelAndView = new ModelAndView("crowdfund/zcDirectPayCrowdfund");
        page.setLimit(20);
        ProjectWithAuthor author = new ProjectWithAuthor();
        author.setEventId(projectWithAuthor.getEventId());
        author.setPayType(0);
        List<ProjectForActivityOutput> projectForActivityOutputList =
                projectBizService.projectForActivityList(author, null, "");

        Integer isSuccess = projectWithAuthor.getIsSuccess();
        if (null != projectWithAuthor.getIsSuccess() && 0 == projectWithAuthor.getIsSuccess()) { // 众筹中
            projectWithAuthor.setIsSuccess(10);
        }

        projectWithAuthor.setPayType(1);
        List<ProjectForActivityOutput> list = projectBizService.projectForActivityList(projectWithAuthor, page, "");
        list.stream().forEach(directPay -> {
            SupportWithMember supportWithMember = new SupportWithMember();
            supportWithMember.setProjectId(directPay.getId());
            List<SupportWithMember> tempList = supportService.findByProjectId(directPay.getId());
            if (tempList != null && tempList.size() > 0) {
                Support support = tempList.get(0);
                directPay.setSupportId(support.getId());
            }
            String filePath = fileBizService.getUploadCIPath("directPay", directPay.getAuthorId());
            String dpCodeUrl = cosBizService.getPreviewPictureUrl(filePath + directPay.getId());
            directPay.setQrCodeUrl(dpCodeUrl);//直接付款众筹详情二维码
            directPay.setUrl(projectBizService.getDirectPayUrl(directPay.getId()));//查看链接
        });
        Integer representNum = distributorRelationService.countForEvent(projectWithAuthor.getEventId());
        projectWithAuthor.setIsSuccess(isSuccess);
        // 众筹金额
        modelAndView.addObject("representNum", representNum);
        modelAndView.addObject("projectNum", projectForActivityOutputList.size());
        modelAndView.addObject("directNum", page.getTotalCount());
        modelAndView.addObject("projectWithAuthor", projectWithAuthor);
        modelAndView.addObject("list", list);
        modelAndView.addObject("page", page);
        CrowdfundEvent crowdfundEvent = crowdfundEventService.get(projectWithAuthor.getEventId());
        modelAndView.addObject("crowdfundEvent", crowdfundEvent);
        modelAndView.addAllObjects(orderBizService.getOrderData(projectWithAuthor.getEventId(), 1));
        return modelAndView;
    }

    /**
     * 根据事件查询众筹导出
     *
     * @param projectWithAuthor 查询数据
     * @param response          响应参数
     * @return 交互数据
     */
    @ResponseBody
    @UserOperate(moduleName = "众筹主题-数据查看-众筹列表", behaviorType = BehaviorType.EXPORT)
    @RequestMapping(value = "listForEventExport")
    public AjaxResult listForEventExport(ProjectWithAuthor projectWithAuthor, HttpServletResponse response) {
        //管理员数据权限控制
        Map<String, Object> params = RealmUtils.getMemberAdministrator(new HashMap<>(), memberAdministratorService);
        if (params.containsKey("memberId")) {
            projectWithAuthor.setMemberId(params.get("memberId").toString());
        }
        if (null != projectWithAuthor.getIsSuccess() && 0 == projectWithAuthor.getIsSuccess()) { // 众筹中
            projectWithAuthor.setIsSuccess(10);
        }
        CrowdfundEvent crowdfundEvent = crowdfundEventService.get(projectWithAuthor.getEventId());
        if (null != projectWithAuthor.getPayStatus() && "1".equals(projectWithAuthor.getPayStatus())) {
            projectWithAuthor.setIsSuccess(1);
        }
        String fileName = crowdfundEvent.getName() + "的事项众筹.xlsx";
        List<ProjectForActivityOutput> projectForActivityOutputList = projectBizService.projectForActivityList(projectWithAuthor, null);
        try {
            ExportExcel exportExcel = new ExportExcel(fileName, ProjectForActivityOutput.class).setDataList(projectForActivityOutputList);
            String allPath = excelExportService.getExcelPath(fileName, "project", exportExcel);
            return AjaxResult.success((Object) allPath);
        } catch (IOException e) {
            logger.error("导出众筹异常", e);
        }
        return AjaxResult.error("导出异常");
    }

    /**
     * 根据事件查询直接付款众筹导出
     *
     * @param projectWithAuthor 查询数据
     * @param response          响应参数
     * @return 交互数据
     */
    @ResponseBody
    @UserOperate(moduleName = "众筹主题-数据查看-直接付款列表", behaviorType = BehaviorType.EXPORT)
    @RequestMapping(value = "dpListForEventExport")
    public AjaxResult dpListForEventExport(ProjectWithAuthor projectWithAuthor, HttpServletResponse response) {
        CrowdfundEvent crowdfundEvent = crowdfundEventService.get(projectWithAuthor.getEventId());
        String fileName = crowdfundEvent.getName() + "的直接付款事项众筹.xlsx";
        List<ProjectForActivityOutput> projectForActivityOutputList = projectBizService.projectForActivityList(projectWithAuthor, null);
        try {
            ExportExcel exportExcel = new ExportExcel(fileName, ProjectForActivityOutput.class).setDataList(projectForActivityOutputList);
            String allPath = excelExportService.getExcelPath(fileName, "project", exportExcel);
            return AjaxResult.success((Object) allPath);
        } catch (IOException e) {
            logger.error("导出众筹异常", e);
        }
        return AjaxResult.error("导出异常");
    }

    /**
     * 事项联合发起项目
     *
     * @param relationId 关系编号
     * @param eventId    事件编号
     * @param page       分页参数
     * @return 交互数据
     */
    @RequestMapping(value = "event/listForDistributorId")
    public ModelAndView listEventForDistributorId(String relationId, String eventId, Page page) {
        ModelAndView modelAndView = new ModelAndView("crowdfund/crowdfundList");
        modelAndView.addObject("isMultiple", false);
        modelAndView.addAllObjects(projectBizService.listForDistributorCommonEvent(eventId, relationId, page));
        return modelAndView;
    }


    /**
     * 导出
     *
     * @param relationId 关系
     * @param response   响应数据
     * @return 交互数据
     */
    @ResponseBody
    @UserOperate(moduleName = "众筹主题-数据查看-联合发起的众筹列表", behaviorType = BehaviorType.EXPORT)
    @RequestMapping(value = "event/listForDistributorIdExport")
    public AjaxResult listEventForDistributorIdExport(String relationId, HttpServletResponse response) {
        DistributorRelation distributorRelation = distributorRelationService.get(relationId);
        Member author = memberService.get(distributorRelation.getDistributorId());

        String fileName = author.getRealname() + "联合发起的众筹.xlsx";
        List<ProjectForActivityOutput> projectForActivityOutputList = projectBizService.listForDistributorId(relationId, null);
        try {
            ExportExcel exportExcel = new ExportExcel(fileName, ProjectForActivityOutput.class).setDataList(projectForActivityOutputList);
            String allPath = excelExportService.getExcelPath(fileName, "crowdfund/event", exportExcel);
            return AjaxResult.success((Object) allPath);
        } catch (IOException e) {
            logger.error("导出联合发起的众筹异常", e);
        }
        return AjaxResult.error("导出异常");
    }

    /**
     * 众筹退款
     *
     * @param id 退款编号
     * @return 交互数据
     */
    @ResponseBody
    @UserOperate(moduleName = "众筹项目-数据查看-众筹的列表-全部退款", behaviorType = BehaviorType.REFUND)
    @RequestMapping(value = "refund")
    public AjaxResult refund(String id, HttpServletRequest request) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            boolean canRefund = projectService.isCanRefund(id);
            if (!canRefund) {
                ajaxResult.setDescription("该众筹者已众筹成功，暂不支持退款");
                return ajaxResult;
            }
            projectBizService.refund(id, request.getSession().getId());
        } catch (BusinessException e) {
            ajaxResult.setDescription(e.getMessage());
            return ajaxResult;
        }
        ajaxResult.setSuccess(true);
        return ajaxResult;

    }

    /**
     * 删除众筹
     *
     * @param id 众筹编号
     * @return 交互数据
     */
    @ResponseBody
    @UserOperate(moduleName = "众筹项目-数据查看-众筹列表", behaviorType = BehaviorType.DELETE)
    @RequestMapping(value = "delete")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult delete(String id) {
        boolean result = projectBizService.delete(id);
        if (result) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("删除失败");
        }
    }


    /**
     * 删除联合众筹
     *
     * @param id 分销关系表ID
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "deleteRepresent")
    @UserOperate(moduleName = "众筹项目-数据查看-联合发起人列表", behaviorType = BehaviorType.DELETE)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult deleteRepresent(String id) {
        if (StringUtils.isEmpty(id))
            return AjaxResult.error("传入的联合众筹关系参数为空");
        DistributorRelation distributorRelation = distributorRelationService.get(id);
        Activity activity = activityService.get(distributorRelation.getTargetId());
        boolean result = distributorRelationService.delete(id); //删除分销关系表
        if (result) {
            if (activity != null && activity.getRepresentNum() != null && activity.getRepresentNum() > 0) {
                activity.setRepresentNum(activity.getRepresentNum() - 1);
                activityService.update(activity);
            }
            distributorCountService.deleteByRelationId(id);//删除分销关系详情表
            distributorDetailService.deleteByRelationId(id);//删除分销关系统计表
            return AjaxResult.success();
        } else {
            return AjaxResult.error("删除失败");
        }
    }

    /**
     * 移除众筹事项
     *
     * @param id 编号
     * @return 交互结果
     */
    @ResponseBody
    @RequestMapping(value = "removeEvent")
    public AjaxResult removeEvent(String id) {
        AjaxResult ajaxResult = new AjaxResult();
        Activity activity = activityService.get(id);
        activity.setEventId("");
        activityService.update(activity);
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }


    /**
     * 校正众筹数据
     *
     * @param id 编号
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "revise")
    public AjaxResult revise(String id) {
        try {
            Project project = projectReviseService.reviseFavorer(id);
            projectReviseService.reviseMultiProject(project);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("校正异常", e);
            return AjaxResult.error("校正失败");
        }
    }


    /**
     * 查询发布商的其他众筹
     *
     * @param projectId 众筹编号
     * @return 交互数据
     */
    @RequestMapping(value = "otherProject")
    public ModelAndView otherProject(String projectId) {
        ModelAndView modelAndView = new ModelAndView("crowdfund/otherProject");
        TargetProject targetProject = targetProjectService.findByProjectId(projectId);
        Activity activity = activityService.get(targetProject.getTargetId());
        Project project = projectService.get(projectId);
        List<Activity> list = activityService.otherActivity(activity.getMember(), activity.getId(), project.getAuthorId());
        modelAndView.addObject("list", list);
        modelAndView.addObject("sourceId", projectId);
        return modelAndView;
    }

    /**
     * 转移支持者
     *
     * @param
     * @param
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "dataTransferm")
    public AjaxResult dataTransferm(String sourceId, String targetId) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            projectTransferBizService.transferSupport(sourceId, targetId);
        } catch (BusinessException be) {
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription(be.getMessage());
            return ajaxResult;
        } catch (Exception e) {
            logger.error("转移支持者异常", e);
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription("服务器异常");
            return ajaxResult;
        }
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    @ResponseBody
    @RequestMapping(value = "dataTransfer")
    public AjaxResult dataTransfer(String sourceId, String targetId) {
        AjaxResult ajaxResult = new AjaxResult();
        try {

            Activity activity = activityService.get(targetId);
            Project source = projectService.get(sourceId);

            List<Counterfoil> counterfoils = counterfoilService.list(new Counterfoil(activity.getEventId(),
                    Constant.BUSINESS_TYPE_CROWDFUND));
            if (counterfoils.size() > 1) {
                // 多个票据，且没有报名。则不能转移，因为不知道自动报名时，报名哪个票据
                Project myProject = projectService.getMyProject(targetId, source.getAuthorId());
                if (null == myProject) {
                    throw new BusinessException("目标项目存在多个票据,不能转移");
                }
                CounterfoilBusiness counterfoilBusiness = counterfoilBusinessService.findByBusinessId(myProject.getId());
                if (null != counterfoilBusiness) {
                    Counterfoil counterfoil = counterfoilService.get(counterfoilBusiness.getCounterfoilId());
                    if (source.getActualAmount() > counterfoil.getPayment()) {
                        throw new BusinessException("转移后的金额大于目标金额,不能转移");
                    }
                }
            } else if (counterfoils.size() == 1) {
                if (source.getActualAmount() > counterfoils.get(0).getPayment()) {
                    throw new BusinessException("转移后的金额大于目标金额,不能转移");
                }
            } else if (counterfoils.size() == 0) {
                throw new BusinessException("该项目不存在票据,不能转移");
            }

            Project target = projectService.findByTargetWithAuthor(targetId, source.getAuthorId());
            //已经报名
            if (null != target) {
                if (1 == target.getPayType()) {
                    throw new BusinessException("该用户在该项目报名方式为直接付款不可转移");
                }

                if (Constant.IS_CROWFUND_ING.equals(target.getIsSuccess())) {
                    //验证众筹金额
                    float realAmount = BigDecimalUtils.add(target.getActualAmount(), source.getActualAmount());
                    realAmount = BigDecimalUtils.round(realAmount, 2);
                    if (realAmount > target.getTargetAmount()) {
                        throw new BusinessException("转移后的金额大于目标金额,不能转移");
                    }
                } else {
                    throw new BusinessException("该用户在该项目已经报名,且状态不对，请核对众筹状态");
                }
            }

            SupportTransfer supportTransfer = new SupportTransfer();
            supportTransfer.setTargetId(targetId);
            supportTransfer.setSourceId(sourceId);
            String id = supportTransferService.insert(supportTransfer);
            if (null == id || id == "") {
                ajaxResult.setSuccess(false);
                ajaxResult.setDescription("转移支持者异常");
                return ajaxResult;
            } else {

                source.setTransferStatus(1);
                projectService.update(source);
            }
        } catch (BusinessException be) {
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription(be.getMessage());
            return ajaxResult;
        } catch (Exception e) {
            logger.error("转移支持者异常", e);
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription("转移异常");
            return ajaxResult;
        }
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }


    @ResponseBody
    @RequestMapping(value = "initLastSupportDate")
    public AjaxResult initLastSupportDate() {
        projectBizService.initLastSupportDate();
        return AjaxResult.success();
    }

    /***
     * 众筹者转移初始化LastSupportDate
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "transferLastSupportDate")
    public AjaxResult transferLastSupportDate() {
        List<Project> projectList = projectService.transferLastSupportDate();
        for (Project project : projectList) {
            List<SupportWithMember> byProjectId = supportService.findByProjectId(project.getId());
            SupportWithMember supportWithMember = byProjectId.get(0);
            if (supportWithMember != null) {
                project.setLastSupportDate(supportWithMember.getCreateDate());
                projectService.update(project);
            }
        }
        return AjaxResult.success();
    }

    @ResponseBody
    @RequestMapping(value = "initZcUseTime")
    public AjaxResult initZcUseTime() {
        projectBizService.updateZcUseTime();
        return AjaxResult.success();
    }

    /***
     * 手动更新众筹用时
     * @param id    projectId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "updateZcUseTime")
    public AjaxResult updateZcUseTime(String id) {
        try {
            Project project = projectService.get(id);
            logger.info("project----:{}", JSONObject.toJSONString(project));
            Project p = new Project();
            p.setId(project.getId());
            long now = DateUtils.getTodayDate().getTime();
            long createDate = project.getCreateDate().getTime();
            if (project.getIsSuccess() == 0) {
                logger.info("project-----进来1");
                p.setUseTime(now - createDate);
            } else if (project.getIsSuccess() == 1) {
                if (project.getLastSupportDate() != null) {
                    logger.info("project-----进来2");
                    List<SupportTransfer> transferList = supportTransferService.getByTargetProId(project.getId());
                    //如果该project不是转移过来的  才更新useTime
                    if (transferList.size() < 1) {
                        logger.info("project-----进来3");
                        p.setUseTime(project.getLastSupportDate().getTime() - createDate);
                        logger.info("project-----userTime：{}", p.getUseTime());
                    } else {
                        logger.info("project-----进来4");
                        p.setUseTime(Long.valueOf(60000));
                    }
                }
            }
            if (p.getUseTime() != null) {
                projectService.update(p);

                logger.info("project-----pppp:{}", JSONObject.toJSONString(p));
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("更新众筹用时异常", e);
            return AjaxResult.error("更新众筹用时异常");
        }
    }


    /**
     * 设置佣金，发起流程
     *
     * @param brokerage
     * @return
     */
    @ResponseBody
    @RequestMapping("updateBrokerage")
    public AjaxResult updateBrokerage(ProjectBrokerage brokerage) {
        try {
            if (StringUtils.isEmpty(brokerage.getTargetId())) {
                return AjaxResult.error("当前众筹项目没有合伙人");
            }
            TargetCopartner targetCopartner = targetCopartnerService.findByTargetId(brokerage.getTargetId());
            if (targetCopartner == null) {
                return AjaxResult.error("当前众筹项目没有合伙人");
            }
            businessInstanceBizService.saveInstanceBiz(brokerage, targetCopartner);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("设置佣金异常", e);
        }
        return AjaxResult.error("设置佣金异常");
    }

    @ResponseBody
    @RequestMapping("initQrCode")
    public AjaxResult initQrCode() {
        List<Project> projects = projectService.list(new Project());
        for (Project project : projects) {
            TargetProject targetProject = targetProjectService.findByProjectId(project.getId());
            Activity activity = activityService.get(targetProject.getTargetId());

            String filePath = fileBizService.getUploadCIPath("crowdfund", project.getAuthorId());
            String content = "project/project_detail.html?id=" + project.getId();
            fileBizService.uploadCloudOut(project.getId(), filePath, content, activity.getMember());
        }
        return AjaxResult.success();
    }

    /**
     * 检查二维码是否存在，不存在上传
     *
     * @param projectId
     * @return
     */
    @ResponseBody
    @RequestMapping("checkQrCode")
    public AjaxResult checkQrCode(String projectId) {
        if (StringUtils.isNotEmpty(projectId)) {
            Project project = projectService.get(projectId);
            try {
                TargetProject targetProject = targetProjectService.findByProjectId(projectId);
                Activity activity = activityService.get(targetProject.getTargetId());

                String filePath = fileBizService.getUploadCIPath("crowdfund", project.getAuthorId());
                String content = "project/project_detail.html?id=" + projectId;
                CrowdfundEvent crowdfundEvent = crowdfundEventService.findByProjectId(projectId);
                if (null != crowdfundEvent && YesNoStatus.YES.getCode().equals(crowdfundEvent.getIsMultiple())) {
                    content = "project/project_multi_detail.html?id=" + projectId;
                }
                String previewPicUrl = fileBizService.uploadCloudOut(projectId, filePath, content, activity.getMember());
                if (previewPicUrl == null) {
                    logger.error("生成众筹详情二维码异常——众筹项目id= " + activity.getId() + "——众筹id=" + projectId);
                    return AjaxResult.error("异常");
                }
            } catch (Exception e) {
                logger.error("生成众筹详情二维码异常", e);
                return AjaxResult.error("异常");
            }
        }
        return AjaxResult.success();
    }


    /**
     * 查询子级列表
     *
     * @param projectWithAuthor 查询参数
     * @param page              分页参数
     * @return 列表数据
     */
    @RequestMapping(value = "childList")
    public ModelAndView childList(ProjectWithAuthor projectWithAuthor, Page page) {
        ModelAndView modelAndView = new ModelAndView("/activity/zcChildList");
        Project project = projectService.get(projectWithAuthor.getId());
        TargetProject targetProject = targetProjectService.findByProjectId(project.getId());
        projectWithAuthor.setBrokerage(1f);
        projectWithAuthor.setParentId(project.getAuthorId());
        projectWithAuthor.setTargetId(targetProject.getTargetId());
        List<ProjectForActivityOutput> projectForActivityOutputList = projectBizService.projectForActivityList(projectWithAuthor, page, null);
        modelAndView.addObject("list", projectForActivityOutputList);
        modelAndView.addObject("page", page);
        modelAndView.addObject("projectWithAuthor", projectWithAuthor);
        return modelAndView;
    }

    /**
     * 通过项目Id查询发布商的其他众筹
     *
     * @param activityId 项目Id
     * @return 交互数据
     */
    @RequestMapping(value = "doOtherProject")
    public ModelAndView queryOtherProject(@RequestParam(value = "activityId") String activityId) {
        ModelAndView modelAndView = new ModelAndView("crowdfund/doOtherProject");
/*        Activity activity = activityService.get(activityId);
        List<Activity> list = activityService.otherActivity(activity.getMember(), activity.getId());*/
        List<Activity> list = activityService.findByIdActivitys(activityId);
        modelAndView.addObject("list", list);
        modelAndView.addObject("sourceId", activityId);
        return modelAndView;
    }

    /**
     * 批量转移支持者
     *
     * @param
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "databatchTransferm")
    public AjaxResult databatchTransferm(String sourceId, String targetId) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            projectTransferBizService.batchTransferSupport(sourceId, targetId);
        } catch (BusinessException be) {
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription(be.getMessage());
            return ajaxResult;
        } catch (Exception e) {
            logger.error("转移支持者异常", e);
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription("服务器异常");
            return ajaxResult;
        }
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }
    /*    *//**
     * 转移众筹成功下的支持者
     *
     * @param
     * @return 交互数据
     *//*
    @ResponseBody
    @RequestMapping(value = "dataTransferZCSuccessful")
    public AjaxResult dataTransferZCSuccessful(String sourceId,String targetId) {
        AjaxResult ajaxResult = new AjaxResult();
        try {

            Activity activity = activityService.get(targetId);
            Project source = projectService.get(sourceId);

            //根据目标和发起人查询
            Project target = projectService.findByTargetWithAuthor(targetId, source.getAuthorId());
            if(source.getActualAmount() > activity.getPrice()){
                throw new BusinessException("转移后的金额大于目标金额,不能转移");
            }
            //已经报名
            if (null != target){
                if (Constant.IS_CROWFUND_ING.equals(target.getIsSuccess())){
                    //验证众筹金额
                    float realAmount = BigDecimalUtils.add(target.getActualAmount(), source.getActualAmount());
                    realAmount = BigDecimalUtils.round(realAmount, 2);
                    if ( realAmount  > target.getTargetAmount()){
                        throw new BusinessException("转移后的金额大于目标金额,不能转移");
                    }
                    projectTransferService.transfer(sourceId, target.getId());

                }else {
                    throw new BusinessException("该用户在该项目已经报名,且状态不对，请核对众筹状态");
                }
            }else{
                // 自动报名
                String projectId = projectBizService.apply(activity, source);
                projectTransferService.transfer(sourceId, projectId);
            }

            List<SupportWithMember> tranAfterList = supportService.findByProjectId(sourceId);
            if(tranAfterList.size() == 0){
                //转移已授权
                SupportTransfer supportTransfer = new SupportTransfer();
                supportTransfer.setTargetId(targetId);
                supportTransfer.setSourceId(sourceId);
                supportTransfer.setIsAuthorized(YET_AUTHORIZED);
                supportTransferService.insert(supportTransfer);

                //众筹项目转移成功
                Project project = projectService.get(sourceId);
                project.setTransferStatus(YET_SUCCESS);
                projectService.update(project);

            }
        } catch (BusinessException be) {
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription(be.getMessage());
            return ajaxResult;
        }catch (Exception e){
            logger.error("转移支持者异常", e);
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription("转移异常");
            return ajaxResult;
        }
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }*/

    /**
     * 查询发布商的其他众筹
     *
     * @param projectId 众筹编号
     * @return 交互数据
     */
    @RequestMapping(value = "otherSuccessfulProject")
    public ModelAndView otherSuccessfulProject(String projectId) {
        ModelAndView modelAndView = new ModelAndView("crowdfund/otherSuccessfulProject");
        TargetProject targetProject = targetProjectService.findByProjectId(projectId);
        Activity activity = activityService.get(targetProject.getTargetId());
        List<Activity> list = activityService.otherActivity(activity.getMember(), activity.getId(), null);
        modelAndView.addObject("list", list);
        modelAndView.addObject("sourceId", projectId);
        return modelAndView;
    }

    /**
     * 根据支持订单id找众筹者信息
     *
     * @param orderId 订单id
     * @return 众筹者信息
     */
    @ResponseBody
    @RequestMapping("getProjectAuthorByOrder")
    public AjaxResult getProjectAuthorByOrder(String orderId) {
        try {
            ProjectWithAuthor projectWithAuthor = projectService.getProjectAuthorByOrder(orderId);
            return AjaxResult.success(projectWithAuthor);
        } catch (Exception e) {
            return AjaxResult.error("查找众筹者失败");
        }
    }

    /**
     * 获取众筹成功海报
     *
     * @param projectId 众筹编号
     * @return
     */
    @ResponseBody
    @RequestMapping("getProjectPoster")
    public AjaxResult getProjectPoster(String projectId) {
        long start = System.currentTimeMillis();
        if (StringUtils.isEmpty(projectId)) {
            return AjaxResult.error("众筹编号不能为空");
        }

        try {
            String posterUrl = projectBizService.getProjectPoster(projectId);
            long end = System.currentTimeMillis();
            return AjaxResult.success(posterUrl);
        } catch (BusinessException e) {
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("获取海报路径异常");
        }
    }


    /**
     * @Description:获取海报
     * @Param: [projectId]
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019-01-23-0023
     */
    @ResponseBody
    @RequestMapping("getNewYearPoster")
    public AjaxResult getNewYearPoster(String projectId) {

        try {
            if (StringUtils.isEmpty(projectId)) {
                return AjaxResult.error("众筹编号不能为空");
            }
            Project project = projectService.get(projectId);
            if (YesNoStatus.YES.getCode().equals(project.getIsSuccess())) {
                return AjaxResult.error("众筹成功,不能获取海报");
            }
            String posterUrl = projectBizService.getNewYearPoster(project);
            return AjaxResult.success(posterUrl);
        } catch (Exception e) {
            logger.error("获取新年海报异常", e);
            return AjaxResult.error("获取新年海报异常");
        }
    }


    /**
     * @Description:获取众筹海报demo
     * @Param: [projectId]
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019-01-23-0023
     */
    @ResponseBody
    @RequestMapping("newYearPosterDemo")
    public AjaxResult newYearPosterDemo(String networkImagePath, String memberId) {
        try {
            MemberGroup member = null;
            if (StringUtils.isEmpty(memberId)) {
                member = RealmUtils.getCurrentUser();
            } else {
                member = memberGroupService.get(memberId);
            }
            if (null == member) {
                return AjaxResult.error("用户不存在");
            }
            String posterUrl = projectBizService.newYearPosterDemo(networkImagePath, member.getId());
            return AjaxResult.success(posterUrl);
        } catch (Exception e) {
            logger.error("获取众筹海报demo异常", e);
            return AjaxResult.error("获取众筹海报demo异常");
        }
    }

    /** 
    * @Description: 获取目标项目 
    * @Param:  sourceId
    * @return: com.party.web.web.dto.AjaxResult
    * @Author: Hua Qunhao
    * @Date: 2019-05-08-0008 
    */
    @ResponseBody
    @RequestMapping("getTargetProject")
    public AjaxResult getTargetProject(String sourceId) {

        Map<String,Object> mmp = new HashMap<>();
        try {
            if(StringUtils.isBlank(sourceId)){
                return AjaxResult.error("项目id不能为空");
            }
            SupportTransfer supportTransfer = supportTransferService.getBySourceId(sourceId);
            if(null==supportTransfer){
                return AjaxResult.error("该项目未转移");
            }

            Activity activity = activityService.get(supportTransfer.getTargetId());

            mmp.put("targetId",activity.getId());
            mmp.put("projectName",activity.getTitle());

            return AjaxResult.success(mmp);
        } catch (Exception e) {
            logger.error("获取目标项目异常", e);
            return AjaxResult.error("获取目标项目异常");
        }
    }
}
